package com.aiyige.utils;

import android.app.Activity;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.aiyige.utils.dialog.LoadingDialog;

/**
 * 安全的{@link AsyncTask},绑定的{@link Activity}一旦{@link Activity#finish()}就不会在执行后处理方法{@link SafeAsyncTask#safeOnPostExecute},并且执行结束后会自动清除Activity引用
 */
public abstract class SafeAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
    private Activity activity;
    private LoadingDialog loadingDialog;

    public SafeAsyncTask(Activity activity, boolean showLoading, String loadingMessage) {
        this.activity = activity;
        if (showLoading) {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(activity)
                    .message(TextUtils.isEmpty(loadingMessage) ? "" : loadingMessage)
                    .cancelable(false)
                    .build();
        } else {
            loadingDialog = null;
        }
    }

    public SafeAsyncTask(Activity activity, int strResId) {
        this(activity, true, StringUtils.getString(strResId));
    }

    public SafeAsyncTask(Activity activity) {
        this(activity, false, "");
    }

    public Activity getActivity() {
        return activity;
    }

    @Override
    protected void onPreExecute() {
        if (loadingDialog != null) {
            loadingDialog.showLoading();
        }
    }

    /**
     * 不要尝试覆盖这个方法，请覆盖{@link #safeOnPostExecute}方法来实现你的逻辑
     */
    @Override
    protected void onPostExecute(Result result) {
        if (!activity.isFinishing()) {
            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }
            safeOnPostExecute(result);
        }
        activity = null;
    }

    /**
     * 这个方法在{@link Activity#finish()}调用后就不会调用
     */
    abstract public void safeOnPostExecute(Result result);

}
